# Copyright (C) 2006-2015 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Miscellaneous CRIS simulator testcases in assembly code, testing
# dv-rv.c and dv-cris.c functions.

# Check whether dv-rv and dv-cris are present.

proc sim_has_rv_and_cris {} {
    global srcdir
    global subdir
    global SIMFLAGS
    global global_as_options
    global global_ld_options
    global global_sim_options

    # We need to assemble and link a trivial program and pass that, in
    # order to test successful exit.

    # A bit of duplication here for the assembling and linking part;
    # what we want to do it to run the simulator without affecting the
    # PASS/FAIL counters, and we can use e.g. run_sim_test for that.

    if ![info exists global_as_options] {
        set global_as_options ""
    }
    if ![info exists global_ld_options] {
        set global_ld_options ""
    }
    if ![info exists global_sim_options] {
        set global_sim_options ""
    }

    set comp_output [target_assemble $srcdir/$subdir/quit.s quit.o \
			 "-I$srcdir/$subdir $global_as_options"]

    if ![string match "" $comp_output] {
	verbose -log "$comp_output" 3
	fail "rv sim test setup (assembling)"
	return 0
    }

    set comp_output [target_link quit.o quit.x "$global_ld_options"]

    if ![string match "" $comp_output] {
	verbose -log "$comp_output" 3
	fail "rv sim test setup (linking)"
	return 0
    }

    set result \
	[sim_run quit.x \
	     "$global_sim_options --hw-device rv --hw-device cris --hw-info" \
	     "" "" ""]
    set return_code [lindex $result 0]
    set output [lindex $result 1]

    if { "$return_code" == "pass" } {
	return 1
    }

    return 0
}

# Similar to slurp_options, but lines are fixed format "^#r ..." (not
# "^#{ws}*r:{ws}+" to avoid intruding on slurp_options syntax).  Only
# trailing whitespace of the "..." is trimmed.  Beware that lines
# including parameters may not contain ":".

proc slurp_rv { file } {
    if [catch { set f [open $file r] } x] {
	#perror "couldn't open `$file': $x"
	perror "$x"
	return -1
    }
    set rv_array {}
    # whitespace expression
    set ws  {[ 	]*}
    # whitespace is ignored at the end of a line.
    set pat "^#r (.*)$ws\$"
    # Allow arbitrary lines until the first option is seen.
    set seen_opt 0
    while { [gets $f line] != -1 } {
	set line [string trim $line]
	# Whitespace here is space-tab.
	if [regexp $pat $line xxx cmd] {
	    # match!
	    lappend rv_array $cmd
	    set seen_opt 1
	} else {
	    if { $seen_opt } {
		break
	    }
	}
    }
    close $f
    return $rv_array
}

# The main test loop.

if [istarget cris*-*-*] {
    global ASFLAGS_FOR_TARGET
    set has_rv_and_cris [sim_has_rv_and_cris]
    global global_as_options
    global global_ld_options
    global global_sim_options

    set saved_global_sim_options $global_sim_options
    set saved_global_ld_options $global_ld_options
    set rvdummy "[file dirname [board_info target sim]]/rvdummy"

    # All machines we test and the corresponding assembler option.
    # We'll only ever test v10 and higher here.

    set combos {{"crisv10" "--march=v10 --no-mul-bug-abort"}
                {"crisv32" "--march=v32"}}

    # We need to pass different assembler flags for each machine.
    # Specifying it here rather than adding a specifier to each and every
    # test-file is preferrable.

    foreach combo $combos {
	set mach [lindex $combo 0]
	set ASFLAGS_FOR_TARGET "[lindex $combo 1]"

	# The .ms suffix is for "miscellaneous .s".
	foreach src [lsort [glob -nocomplain $srcdir/$subdir/*.ms]] {

	    # If we're only testing specific files and this isn't one of them,
	    # skip it.
	    if ![runtest_file_p $runtests $src] {
		continue
	    }

	    # Whoever runs the test should be alerted that not all
	    # testcases have been checked; that's why we do the loop
	    # and don't just return at the top.
	    if !$has_rv_and_cris {
		untested $src
		continue
	    }

	    set sim_defaults "--hw-file $srcdir/$subdir/std.dev"
	    set ld_defaults "--section-start=.text=0"

	    # We parse options an extra time besides in run_sim_test,
	    # to determine if our defaults should be overridden.

	    set opt_array [slurp_options $src]
	    foreach i $opt_array {
		set opt_name [lindex $i 0]
		set opt_machs [lindex $i 1]
		set opt_val [lindex $i 2]

		# Allow concatenating to the default options by
		# specifying a mach.
		if { $opt_name == "sim" && $opt_machs == "" } {
		    set sim_defaults ""
		}

		if { $opt_name == "ld" && $opt_machs == "" } {
		    set ld_defaults ""
		}
	    }

	    set rvdummy_id -1
	    set hostcmds [slurp_rv $src]

	    if { $hostcmds != "" } {
		# I guess we could ask to have rvdummy executed on a
		# remote host, but it looks like too much trouble for
		# a feature rarely used.
		if [is_remote host] {
		    untested $src
		    continue
		}

		set src_components [file split $src]
		set rvfile "[lindex $src_components \
			    [expr [llength $src_components] - 1]].r"

		if [catch { set f [open $rvfile w] } x] {
		    error "$x"
		} {
		    set contents [join $hostcmds "\n"]

		    # Make it possible to use files from the test
		    # source directory; expected with the @-command.
		    regsub -all "@srcdir@" $contents "$srcdir/$subdir" contents

		    verbose "rv: $contents" 2
		    puts $f $contents
		    close $f
		}

		spawn -noecho $rvdummy "$rvfile"
		if { $spawn_id < 0 } {
		    error "Couldn't spawn $rvdummy"
		    continue
		}
		set rvdummy_id $spawn_id
	    }

	    # Unfortunately this seems like the only way to pass
	    # additional sim, ld etc. options to run_sim_test.
	    set global_sim_options "$saved_global_sim_options $sim_defaults"
	    set global_ld_options "$saved_global_ld_options $ld_defaults"
	    run_sim_test $src $mach
	    set global_sim_options $saved_global_sim_options
	    set global_ld_options $saved_global_ld_options

	    # Stop the rvdummy, if it's still running.  We need to
	    # wait on it anyway to avoid it turning into a zombie.
	    if { $rvdummy_id != -1 } {
		close -i $rvdummy_id
		wait -i $rvdummy_id

		# Gleaned from framework.exp, this seems an indicator
		# to whether the test had expected outcome.  If so, we
		# want to remove the rv-file.
		if { $exit_status == 0 } {
		    file delete $rvfile
		}
	    }
	}
    }
}
